<?php
	include 'commonAccountFunctions.php';

	$username = $_REQUEST['userName'];
	$pwd = $_REQUEST['password'];
	$conPwd = $_REQUEST['verifyPassword'];
	$email = $_REQUEST['emailAddress'];
	$conEmail = $_REQUEST['verifyEmail'];
	$auth = $_REQUEST['authorization'];
	
	if(!pwdsMatch($pwd, $conPwd) || !validateEmails($email, $conEmail)){ // checks for password and e-mail validity
		header('Location: manageUserAccounts.php');
	} elseif(userExists($username)){ // username is taken
		header('Location: manageUserAccounts.php');
	} elseif(trim($pwd)==""){ // cannot create accounts with a blank password
		header('Location: manageUserAccounts.php');
	} elseif($username==""){ // in case someone decides to visit this URL, it will not create a blank account
		header('Location: manageUserAccounts.php');
	} else{
		setAccount($username, $pwd, $auth, $email);
		//$filepath = "../user-accounts/$username.txt";
		//file_put_contents($filepath, hash("sha256", $pwd));
		//file_put_contents($filepath, "\n$auth", FILE_APPEND);
		//file_put_contents($filepath, "\n$email", FILE_APPEND);
	}
	
	// user created, returns to manageUserAccounts.php
	header('Location: manageUserAccounts.php');
	
	// pwdsMatch: string, string -> boolean
	// returns true if the passwords match
	// otherwise, returns false
	function pwdsMatch($pwd, $conpwd){
		return $pwd===$conpwd;
	}
	
	// validateEmails: string, string -> boolean
	// returns false if the e-mail does not match the regular expression
	// returns false if the e-mail passes the regular expression but the email and vemail do not match
	// otherwise, returns true
	function validateEmails($email, $vemail){
		$patt='/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/';
		if(!preg_match($patt, $email)){ // if the e-mail does not match the expresion
			return false;
		}
		return $email===$vemail;
	}
?>